﻿using System;
using System.Web.UI;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.ReportManagement
{
    public partial class ReportClient : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();
            if (!IsPostBack)
            {
                BindData();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            ButtonSearchClick(null, null);
            ListViewClient.DataBind();
        }
        /// <summary>
        /// Filter search clients
        /// </summary>
        protected void FilterClient()
        {
            var fullName = textFullName.Text;
            var companyName = textCompanyName.Text;
            if (string.IsNullOrEmpty(fullName) && string.IsNullOrEmpty(companyName))
            {
                DataBind();
            }
            else
            {
                labelResultSearch.Text = string.Empty;
                var query = ClientProfileLogic.SearchClient(fullName, companyName);
                Session["SOURCE_CLIENT_TABLE"] = query;
                ListViewClient.DataSource = query;
                ListViewClient.DataBind();                
            }
        }
        private void BindData()
        {
            var result = ClientProfileLogic.SelectAllClient();
            Session["SOURCE_CLIENT_TABLE"] = result;
            ListViewClient.DataSource = result;
            ListViewClient.DataBind();
        }
        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.AllReport;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }

        protected void ButtonSearchClick(object sender, EventArgs e)
        {
            FilterClient();
        }

        protected void ButtonCreateReportClick(object sender, EventArgs e)
        {
            Response.Redirect("ShowReportClients.aspx");
        }
    }
}
